#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QSysInfo>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setMaximumWidth(400);
    //this->setMinimumHeight(200);
    sysType =  QSysInfo::productType();

    if(sysType == "osx")
        filePre = "../../../../data/";
    else
        filePre = "../data";

    initMainUI();
    system = new System();
    readUser(filePre + "user.txt");
    readAttr(filePre + "attr.txt");
}

void MainWindow::initMainUI()
{
    // 主页
    mainLayout = new QVBoxLayout();

    btnReg = new QPushButton("注册");
    btnLogin = new QPushButton("登录");
    btnShow = new QPushButton("显示景点信息");
    btnPre = new QPushButton("预约");
    btnCancel = new QPushButton("取消预约");
    btnManger = new QPushButton("管理员统计");
    btnExit = new QPushButton("退出");

    mainLayout->addWidget(btnReg);
    mainLayout->addWidget(btnLogin);
    mainLayout->addWidget(btnShow);
    mainLayout->addWidget(btnPre);
    mainLayout->addWidget(btnCancel);
    mainLayout->addWidget(btnManger);
    mainLayout->addWidget(btnExit);

    mainWidget = new QWidget();
    mainWidget->setLayout(mainLayout);
    setCentralWidget(mainWidget);
    //ui->centralwidget->setLayout(mainLayout);
    // 绑定信号
    connect(btnReg, SIGNAL(clicked()), this, SLOT(slotReg()));
    connect(btnLogin, SIGNAL(clicked()), this, SLOT(slotLogin()));
    connect(btnShow, SIGNAL(clicked()), this, SLOT(slotBtnShowAttr()));
    connect(btnPre, SIGNAL(clicked()), this, SLOT(slotBtnPreAttr()));
    connect(btnCancel, SIGNAL(clicked()), this, SLOT(slotBtnCancel()));
    connect(btnManger, SIGNAL(clicked()), this, SLOT(slotBtnManager()));
    connect(btnExit, SIGNAL(clicked()), this, SLOT(slotBtnExit()));
}

void MainWindow::initRegUI()
{
    // 注册
    regLayout = new QVBoxLayout();

    QVBoxLayout *vLayout1 = new QVBoxLayout();
    QVBoxLayout *vLayout2 = new QVBoxLayout();
    labelUser = new QLabel("用户名:");
    labelName = new QLabel("姓名:");
    labelContact = new QLabel("联系方式:");
    labelID = new QLabel("身份证号:");
    labelType = new QLabel("证件类型:");
    labelAdmin = new QLabel("是否管理员:");

    vLayout1->addWidget(labelUser);
    vLayout1->addWidget(labelName);
    vLayout1->addWidget(labelContact);
    vLayout1->addWidget(labelID);
    vLayout1->addWidget(labelType);
    vLayout1->addWidget(labelAdmin);

    editUser = new QLineEdit();
    editName = new QLineEdit();
    editContact = new QLineEdit();
    editID = new QLineEdit();
    comboType = new QComboBox();
    comboType->addItem("身份证");
    comboType->addItem("学生证");
    comboAdmin = new QComboBox();
    comboAdmin->addItem("否");
    comboAdmin->addItem("是");

    vLayout2->addWidget(editUser);
    vLayout2->addWidget(editName);
    vLayout2->addWidget(editContact);
    vLayout2->addWidget(editID);
    vLayout2->addWidget(comboType);
    vLayout2->addWidget(comboAdmin);

    QWidget *widget1 = new QWidget();
    widget1->setLayout(vLayout1);
    QWidget *widget2 = new QWidget();
    widget2->setLayout(vLayout2);

    QWidget *widget3 = new QWidget();
    QHBoxLayout *hLayout1 = new QHBoxLayout();
    hLayout1->addWidget(widget1);
    hLayout1->addWidget(widget2);
    widget3->setLayout(hLayout1);

    regLayout->addWidget(widget3);
    btnRegSure = new QPushButton("确认");
    btnRegCancel = new QPushButton("取消");
    regLayout->addWidget(btnRegSure);
    regLayout->addWidget(btnRegCancel);

    regWidget = new QWidget();
    regWidget->setLayout(regLayout);
    setCentralWidget(regWidget);

    connect(btnRegSure, SIGNAL(clicked()), this, SLOT(slotRegSure()));
    connect(btnRegCancel, SIGNAL(clicked()), this, SLOT(slotBtnBack()));
}

void MainWindow::initLoginUI()
{
    loginLayout = new QVBoxLayout();
    QLabel *label = new QLabel("请输入用户名");
    editLoginUser = new QLineEdit();
    btnLoginSure = new QPushButton("登录");
    btnLoginCancel = new QPushButton("取消");

    editLoginUser->setFocus();
    loginLayout->addWidget(label);
    loginLayout->addWidget(editLoginUser);
    loginLayout->addWidget(btnLoginSure);
    loginLayout->addWidget(btnLoginCancel);

    loginWidget = new QWidget();
    loginWidget->setLayout(loginLayout);
    setCentralWidget(loginWidget);
    connect(btnLoginSure, SIGNAL(clicked()), this, SLOT(slotBtnLoginSure()));
    connect(btnLoginCancel, SIGNAL(clicked()), this, SLOT(slotBtnBack()));
}

void MainWindow::initAttractionUI()
{
    // 创建滚动区
    QScrollArea *scrollArea = new QScrollArea();
    //scrollArea->setContentsMargins(0,0,0,0);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scrollArea->setWidgetResizable(true);
    scrollArea->setGeometry(QRect(0, 50, this->width(), this->height()));
    // 创建widget
    QWidget *scrollWidget = new QWidget();
    //scrollWidget->setContentsMargins(0,0,0,0);
    // 给widget设置布局
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
    //scrollLayout->setMargin(0);
    // 加入子控件， 默认使用软件主页
    labelAttrName = new QLabel("景区名称:\n");
    labelAttrDesc = new QLabel("景区描述:\n");
    labelAttrPrice= new QLabel("景区价格:\n");
    labelAttrPerson = new QLabel("预约情况:\n");

    QColor color[2] = {Qt::red, Qt::blue};
    QPalette palette;
    for(int i=0; i<system->attractions.length(); i++)
    {
        // 读取内容
        QString name = system->attractions.at(i).name;
        QString desc = system->attractions.at(i).description;
        QString type1 = system->attractions.at(i).ticket_types["free"].ticket_type;
        QString type2 = system->attractions.at(i).ticket_types["half"].ticket_type;
        QString type3 = system->attractions.at(i).ticket_types["full"].ticket_type;
        double price_1 = system->attractions.at(i).ticket_types["free"].price;
        double price_2 = system->attractions.at(i).ticket_types["half"].price;
        double price_3 = system->attractions.at(i).ticket_types["full"].price;
        int day_limit = system->attractions.at(i).daily_limit;
        int book_today = system->attractions.at(i).booked_today;
        // 创建控件
        QLabel *label1 = new QLabel("景区名称:\n\t" + name);
        QLabel *label2  = new QLabel("景区描述:\n\t" + desc);
        QLabel *label3 = new QLabel("景区价格:\n\t" +
                                    type1 + ":  " + QString::number(price_1) + "\n\t" +
                                    type2 + ":  " + QString::number(price_2) + "\n\t" +
                                    type3 + ":  " + QString::number(price_3) + "\n\t"
                                    );
        QLabel *label4  = new QLabel(QString("预约情况:\n\t") +
                                     "最大预约:" + QString::number(day_limit) + "\n\t" +
                                     "今日预约:" + QString::number(book_today)
                                     );
        // 加入控件
        scrollLayout->addWidget(label1);
        scrollLayout->addWidget(label2);
        scrollLayout->addWidget(label3);
        scrollLayout->addWidget(label4);
        // 设置颜色
        palette.setColor(QPalette::WindowText, color[i%2]);
        label1->setPalette(palette);
        label2->setPalette(palette);
        label3->setPalette(palette);
        label4->setPalette(palette);

        QLabel *line = new QLabel();
        line->setMinimumHeight(3);
        line->setStyleSheet("QLabel{background-color:rgb(200,200,247);}");
        scrollLayout->addWidget(line);
    }

    // 返回按钮
    btnAttrBack = new QPushButton("返回");
    scrollLayout->addWidget(btnAttrBack);
    connect(btnAttrBack, SIGNAL(clicked()), this, SLOT(slotBtnBack()));
    // 设置滚动区核心控件为widget
    scrollArea->setWidget(scrollWidget);
    setCentralWidget(scrollArea);
}

void MainWindow::initPreAttrUI()
{
    QVBoxLayout *layout = new QVBoxLayout();
    preAttrWidget = new QWidget();
    QLabel *label1 = new QLabel("请输入用户名");
    preAttrUser = new QLineEdit();
    QLabel *label2 = new QLabel("请选择景点");
    preAttrCom = new QComboBox();
    preAttrRes = new QLabel();
    preAttrBack = new QPushButton("返回");
    preAttrSure = new QPushButton("预约");

    layout->addWidget(label1);
    layout->addWidget(preAttrUser);
    layout->addWidget(label2);
    layout->addWidget(preAttrCom);
    layout->addWidget(preAttrRes);
    layout->addWidget(preAttrSure);
    layout->addWidget(preAttrBack);
    connect(preAttrSure, SIGNAL(clicked()), this, SLOT(slotBtnPreAttrSure()));
    connect(preAttrBack, SIGNAL(clicked()), this, SLOT(slotBtnBack()));

    for(int i=0; i<system->attractions.length(); i++)
    {
        preAttrCom->addItem(system->attractions.at(i).name);
    }

    preAttrWidget->setLayout(layout);
    setCentralWidget(preAttrWidget);
}

void MainWindow::initCancelUI()
{
    cancelWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout();
    QLabel *label1 = new QLabel("请输入用户名");
    cancelUser = new QLineEdit();
    QLabel *label2 = new QLabel("请选择要取消的景区");
    cancelCom = new QComboBox();
    cancelSure = new QPushButton("确定取消");
    cancelBack = new QPushButton("返回");

    layout->addWidget(label1);
    layout->addWidget(cancelSure);
    layout->addWidget(label2);
    layout->addWidget(cancelCom);
    layout->addWidget(cancelSure);
    layout->addWidget(cancelBack);

    for(int i=0; i<system->attractions.length(); i++)
    {
        cancelCom->addItem(system->attractions.at(i).name);
    }
    connect(cancelSure, SIGNAL(clicked()), this, SLOT(slotBtnCancelSure(0)));
    connect(cancelBack, SIGNAL(clicked()), this, SLOT(slotBtnBack()));

    cancelWidget->setLayout(layout);
    setCentralWidget(cancelWidget);
}

void MainWindow::initManagerUI()
{
    managerWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout();

    // 创建滚动区
    QScrollArea *scrollArea = new QScrollArea();
    //scrollArea->setContentsMargins(0,0,0,0);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scrollArea->setWidgetResizable(true);
    scrollArea->setGeometry(QRect(0, 50, this->width(), this->height()));
    // 创建widget
    QWidget *scrollWidget = new QWidget();
    //scrollWidget->setContentsMargins(0,0,0,0);
    // 给widget设置布局
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);

    QColor color[2] = {Qt::red, Qt::blue};
    QPalette palette;
    for(int i=0; i<system->attractions.length(); i++)
    {
        // 读取内容
        int day_limit = system->attractions.at(i).daily_limit;
        int book_today = system->attractions.at(i).booked_today;
        QString name = system->attractions.at(i).name;
        // 创建控件
        QLabel *label  = new QLabel("景区: " + name + "\n" +
                                    QString("预约情况:\n") +
                                    "\t最大预约:" + QString::number(day_limit) + "\n" +
                                    "\t今日预约:" + QString::number(book_today)
                                    );
        // 加入控件
        scrollLayout->addWidget(label);
        // 设置颜色
        palette.setColor(QPalette::WindowText, color[i%2]);
        label->setPalette(palette);

        QLabel *line = new QLabel();
        line->setMaximumHeight(3);
        line->setStyleSheet("QLabel{background-color:rgb(200,200,247);}");
        scrollLayout->addWidget(line);
    }

    // 返回按钮
    managerBack = new QPushButton("返回");
    scrollLayout->addWidget(managerBack);
    connect(managerBack, SIGNAL(clicked()), this, SLOT(slotBtnBack()));
    // 设置滚动区核心控件为widget
    scrollArea->setWidget(scrollWidget);
    setCentralWidget(scrollArea);
}

void MainWindow::writeUser(QString path, QString content)
{
    QFile file(path);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&file);
    ts.setCodec("UTF-8");
    ts << content << "\n";
    file.close();
}
void MainWindow::readUser(QString path)
{
    QFile file(path);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            // 处理每一行数据
            QList<QString> list =  line.split("#");
            system->register_visitor(list.at(1), list.at(2), list.at(3), list.at(4), list.at(5), list.at(6).toInt());
        }
        file.close();
    }
    qDebug() << system->visitors.length();
}

void MainWindow::readAttr(QString path)
{
    QFile file(path);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            // 处理每一行数据
            QList<QString> list =  line.split("#");
            system->attractions << Attraction(list.at(1), list.at(2), list.at(3).toInt(), list.at(4).toInt(), list.at(5).toDouble(), list.at(6).toDouble());
        }
        file.close();
    }
    qDebug() << system->visitors.length();
}
void MainWindow::writeAttr(QString path, QString content)
{
    QFile file(path);
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream ts(&file);
    ts.setCodec("UTF-8");
    ts << content;
    file.close();
}
void MainWindow::slotReg()
{
    initRegUI();
    //setCentralWidget(regWidget);
}

void MainWindow::slotRegSure()
{
    // 提取内容
    QString user = editUser->text();
    QString name = editName->text();
    QString contact = editContact->text();
    QString id = editID->text();
    QString type = comboType->currentText();
    bool isAdmin = false;
    if(comboAdmin->currentIndex()==1)
        isAdmin = true;

    QPushButton *okbtn = new QPushButton(QString::fromLocal8Bit("确定"));
    QMessageBox *mymsgbox = new QMessageBox;
    // 判断
    if(user.length()<5 || name.length()<5 || contact.length()!=11 || id.length()!=18)
    {
        mymsgbox->setIcon(QMessageBox::Warning);
        mymsgbox->setWindowTitle(QString::fromLocal8Bit("抱歉"));
        mymsgbox->setText(QString::fromLocal8Bit("请确保用户名大于5个字符，联系方式11位，身份证号18位"));
        mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
        mymsgbox->exec();//阻塞等待用户输入
        if (mymsgbox->clickedButton()==okbtn)//点击了OK按钮
        {
            return;
        }
    }

    // 注册
    system->register_visitor(user, name, contact, id, type, isAdmin);
    // 保存数据
    QString msg;
    msg = "#" + user + "#" + name + "#" + contact + "#"+ id + "#" + type + "#" + QString::number(isAdmin) + "#";
    writeUser(filePre + "/user.txt", msg);
    // 弹窗
    mymsgbox->setIcon(QMessageBox::Warning);
    mymsgbox->setWindowTitle(QString::fromLocal8Bit("恭喜"));
    mymsgbox->setText(QString::fromLocal8Bit("注册成功"));
    mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
    mymsgbox->exec();//阻塞等待用户输入
    if (mymsgbox->clickedButton()==okbtn)//点击了OK按钮
    {
        initMainUI();
    }
}

void MainWindow::slotLogin()
{
    initLoginUI();
}

void MainWindow::slotBtnLoginSure()
{
    QString user;
    user = editLoginUser->text();
    QPushButton *okbtn = new QPushButton(QString::fromLocal8Bit("确定"));
    QMessageBox *mymsgbox = new QMessageBox;

    if(user.length()<5 || system->login(user)==nullptr)
    {
        mymsgbox->setIcon(QMessageBox::Warning);
        mymsgbox->setWindowTitle(QString::fromLocal8Bit("抱歉"));
        mymsgbox->setText(QString::fromLocal8Bit("请输入正确的用户名"));
        mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
        mymsgbox->exec();//阻塞等待用户输入
        if (mymsgbox->clickedButton()==okbtn)//点击了OK按钮
        {
            return ;
        }
    }

    mymsgbox->setIcon(QMessageBox::Warning);
    mymsgbox->setWindowTitle(QString::fromLocal8Bit("恭喜"));
    mymsgbox->setText(QString::fromLocal8Bit("登录成功"));
    mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
    mymsgbox->exec();//阻塞等待用户输入
    if (mymsgbox->clickedButton()==okbtn)//点击了OK按钮
    {
        initMainUI();
    }
}

void MainWindow::slotBtnShowAttr()
{
    initAttractionUI();
}

void MainWindow::slotBtnPreAttr()
{
    initPreAttrUI();
}

void MainWindow::slotBtnPreAttrSure()
{
    QPushButton *okbtn = new QPushButton(QString::fromLocal8Bit("确定"));
    QMessageBox *mymsgbox = new QMessageBox;
    mymsgbox->setIcon(QMessageBox::Warning);
    QPalette palette;
    palette.setColor(QPalette::WindowText, Qt::red);
    mymsgbox->setPalette(palette);

    // 拿到用户名
    QString user = preAttrUser->text();
    QString res;
    for(int i=0; i<system->visitors.length(); i++)
    {
        // 找到用户名
        if(system->login(user)!=nullptr)
        //if(user == system->visitors.at(i).name)
        {
            Visitor visitor = system->visitors.at(i);
            // 根据身份分类设置票价
            QString ticket_type;
            if (visitor.id_type == "身份证") {
                ticket_type = "full";
            }
            else if (visitor.id_type == "学生证") {
                ticket_type = "half";
            }
            else {
                ticket_type = "free";
            }

            if(system->attractions[preAttrCom->currentIndex()].can_book())
            {
                res = QString("可以预约\n");
                system->attractions[preAttrCom->currentIndex()].booked_today++;
                mymsgbox->setWindowTitle(QString::fromLocal8Bit("恭喜"));
                res += "您的票种为:\n" +
                        system->attractions[preAttrCom->currentIndex()].ticket_types[ticket_type].ticket_type +"\n" +
                        "您的票价是:\n" +
                        QString::number(system->attractions[preAttrCom->currentIndex()].ticket_types[ticket_type].price);
                mymsgbox->setText(res);
                mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
                mymsgbox->exec();//阻塞等待用户输入
            }
            else
            {
                res = QString("今日预约已满，不可预约");
                mymsgbox->setWindowTitle(QString::fromLocal8Bit("抱歉"));
                mymsgbox->setText(res);
                mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
                mymsgbox->exec();//阻塞等待用户输入
            }
            return;
        }
    }

    mymsgbox->setWindowTitle(QString::fromLocal8Bit("抱歉"));
    mymsgbox->setText(QString::fromLocal8Bit("用户名不存在"));
    mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
    mymsgbox->exec();//阻塞等待用户输入
}

void MainWindow::slotBtnCancel()
{
    initCancelUI();
}

void MainWindow::slotBtnCancelSure()
{
    QPushButton *okbtn = new QPushButton(QString::fromLocal8Bit("确定"));
    QMessageBox *mymsgbox = new QMessageBox;
    mymsgbox->setIcon(QMessageBox::Warning);
    QPalette palette;
    palette.setColor(QPalette::WindowText, Qt::red);
    mymsgbox->setPalette(palette);

    // 拿到用户名
    QString user = preAttrUser->text();
    QString res;
    for(int i=0; i<system->visitors.length(); i++)
    {
        // 找到用户名
        if(user == system->visitors.at(i).name)
        {
            // 取消预约
            system->attractions[preAttrCom->currentIndex()].booked_today--;
            mymsgbox->setWindowTitle(QString::fromLocal8Bit("恭喜"));
            res += "取消预约成功";
            mymsgbox->setText(res);
            mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
            mymsgbox->exec();//阻塞等待用户输入
            return;
        }
    }

    mymsgbox->setWindowTitle(QString::fromLocal8Bit("抱歉"));
    mymsgbox->setText(QString::fromLocal8Bit("用户名不存在"));
    mymsgbox->addButton(okbtn, QMessageBox::AcceptRole);
    mymsgbox->exec();//阻塞等待用户输入
}

void MainWindow::slotBtnManager()
{
    initManagerUI();
}

void MainWindow::slotBtnBack()
{
    initMainUI();
}

void MainWindow::saveData()
{
    QString msg;

    for(int i=0; i<system->attractions.length(); i++)
    {
        QString name = system->attractions.at(i).name;
        QString desc = system->attractions.at(i).description;
        int lim = system->attractions.at(i).daily_limit;
        int today = system->attractions.at(i).booked_today;
        double full = system->attractions.at(i).ticket_types["full"].price;
        double half = system->attractions.at(i).ticket_types["half"].price;
        msg += "#" + name + "#" + desc + "#" + QString::number(lim) + "#" + QString::number(today) + "#" + QString::number(full) + "#" + QString::number(half) + "#\n";
    }
    // 写入景点预约信息
    writeAttr(filePre + "attr.txt", msg);
}

void MainWindow::slotBtnExit()
{
    saveData();
    QCoreApplication::exit(0);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveData();
    qDebug() << "close window";
}

MainWindow::~MainWindow()
{
    delete ui;
}

